package com.qf.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.pojo.User;
import org.elasticsearch.action.admin.indices.create.CreateIndexRequest;
import org.elasticsearch.action.admin.indices.create.CreateIndexResponse;
import org.elasticsearch.action.bulk.BulkRequest;
import org.elasticsearch.action.bulk.BulkResponse;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.xcontent.XContentBuilder;
import org.elasticsearch.common.xcontent.XContentType;
import org.elasticsearch.common.xcontent.json.JsonXContent;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.util.List;

@Service
public class EsServiceImpl implements EsService {

    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Autowired
    private UserService userService;
    @Autowired
    private ObjectMapper objectMapper;
    /**
     * 创建索引
     *
     *   操作索引   restHighLevelClient.indices()
     *   操作文档   restHighLevelClient.index()
     *
     *   # 创建索引，指定数据结构
     * PUT /book
     * {
     *   "settings": {
     *     # 分片数
     *     "number_of_shards": 5,
     *     # 备份数
     *     "number_of_replicas": 1
     *   },
     *   # 指定数据结构
     *   "mappings": {
     *     # 类型 Type, 我们是7.x版本, 所以没有这个novel, 直接写下面properties数据就可以。
     *     "novel": {
     *       # 文档存储的Field
     *       "properties": {
     *         # Field属性名
     *         "name": {
     *     		# 类型
     *           "type": "text",
     *     		# 指定分词器
     *           "analyzer": "ik_max_word",
     *     		# 指定当前Field可以被作为查询的条件
     *           "index": true ,
     *     		# 是否需要额外存储
     *           "store": false
     *         },
     *         "auth": {
     *           "type": "keyword"
     *         },
     *         "count": {
     *           "type": "long"
     *         },
     *         "createtime": {
     *           "type": "date",
     *            # 时间类型的格式化方式     epoch_millis 毫秒格式
     *           "format": "yyyy-MM-dd HH:mm:ss||yyyy-MM-dd||epoch_millis"
     *         },
     *         "desc": {
     *           "type": "text",
     *           "analyzer": "ik_max_word"
     *         }
     *       }
     *     }
     *   }
     * }
     * @param user
     */
    @Override
    public void createIndexUser(String user) {
        try {
            CreateIndexRequest createIndexRequest = new CreateIndexRequest(user);
            //DSL 语句
            //1.c创建主分片和备份分片
            Settings.Builder settings = Settings.builder()
                    .put("number_of_shards", 5)
                    .put("number_of_replicas", 1);
            //2.创建索引构造
            XContentBuilder mapping = JsonXContent.contentBuilder()
                    .startObject()
                    .startObject("properties")
                    .startObject("name")
                    .field("type", "text")
                    .endObject()
                    .startObject("password")
                    .field("type", "keyword")
                    .endObject()
                    .startObject("sex")
                    .field("type", "keyword")
                    .endObject()
                    .startObject("birthday")
                    .field("type", "date")
                    .field("format", "yyyy-MM-dd")
                    .endObject()
                    .startObject("registTime")
                    .field("type", "date")
                    .field("format", "yyyy-MM-dd HH:mm:ss")
                    .endObject()
                    .endObject()
                    .endObject();
            createIndexRequest.settings(settings);
            createIndexRequest.mapping(String.valueOf(mapping));

            CreateIndexResponse createIndexResponse = restHighLevelClient.indices().create(createIndexRequest, RequestOptions.DEFAULT);
            System.out.println("结果：" + createIndexResponse.isAcknowledged());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    /**
     * 导入数据批量
     * @param user
     */
    @Override
    public void importIndexUser(String user) {
        List<User> userList = userService.findAll();
        BulkRequest bulkRequest = new BulkRequest(user);
        try {
            for (User u : userList) {
                IndexRequest indexRequest = new IndexRequest();
                String json = objectMapper.writeValueAsString(u);
                indexRequest.source(json, XContentType.JSON);
                indexRequest.id(String.valueOf(u.getId()));
                bulkRequest.add(indexRequest);
            }
            //一次性批量提交
            BulkResponse bulkResponse = restHighLevelClient.bulk(bulkRequest, RequestOptions.DEFAULT);
            System.out.println("结果:" + bulkResponse.status());
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
